{% extends "后台管理/template.html" %}

{% block title %}活动参与情况{% endblock %}

{% block css %}
<style>
    .chart-card {
        transition: all 0.3s ease;
        height: 100%;
    }
    
    .chart-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }

    .chart-container {
        min-height: 300px;
        position: relative;
    }

    .filter-card {
        border-radius: 8px;
        margin-bottom: 1.5rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold py-3 mb-4">活动参与情况分析</h4>
        <div class="btn-group">
            <button class="btn btn-primary" onclick="refreshData()">
                <i class="bx bx-refresh me-1"></i> 刷新数据
            </button>
        </div>
    </div>

    <!-- 筛选条件 -->
    <div class="card filter-card">
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">时间范围</label>
                    <select class="form-select" id="timeRange" onchange="loadStatistics()">
                        <option value="7">最近7天</option>
                        <option value="30">最近30天</option>
                        <option value="90">最近90天</option>
                        <option value="365">最近一年</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">活动状态</label>
                    <select class="form-select" id="activityStatus" onchange="loadStatistics()">
                        <option value="">全部状态</option>
                        <option value="published">进行中</option>
                        <option value="ended">已结束</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- 数据概览 -->
    <div class="row g-4 mb-4">
        <div class="col-sm-6 col-xl-2">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">未审核</span>
                            <h3 class="card-title mb-0" id="pendingCount">0</h3>
                        </div>
                        <div class="avatar">
                            <span class="avatar-initial rounded bg-label-warning">
                                <i class="bx bx-time"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-2">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">进行中</span>
                            <h3 class="card-title mb-0" id="ongoingCount">0</h3>
                        </div>
                        <div class="avatar">
                            <span class="avatar-initial rounded bg-label-info">
                                <i class="bx bx-play-circle"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">总参与人数</span>
                            <h3 class="card-title mb-0" id="totalParticipants">0</h3>
                        </div>
                        <div class="avatar">
                            <span class="avatar-initial rounded bg-label-primary">
                                <i class="bx bx-user-check"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">活动总数</span>
                            <h3 class="card-title mb-0" id="totalActivities">0</h3>
                        </div>
                        <div class="avatar">
                            <span class="avatar-initial rounded bg-label-success">
                                <i class="bx bx-calendar-event"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">平均参与率</span>
                            <h3 class="card-title mb-0" id="avgParticipationRate">0%</h3>
                        </div>
                        <div class="avatar">
                            <span class="avatar-initial rounded bg-label-warning">
                                <i class="bx bx-line-chart"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">完成率</span>
                            <h3 class="card-title mb-0" id="completionRate">0%</h3>
                        </div>
                        <div class="avatar">
                            <span class="avatar-initial rounded bg-label-info">
                                <i class="bx bx-check-circle"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 计算说明公告栏 -->
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class='bx bx-info-circle me-2'></i>统计指标说明</h5>
            <button type="button" class="btn btn-icon btn-sm btn-text-secondary rounded-pill" 
                    data-bs-toggle="collapse" data-bs-target="#statsInfo">
                <i class="bx bx-chevron-down"></i>
            </button>
        </div>
        <div class="collapse show" id="statsInfo">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="fw-bold">基础指标</h6>
                        <ul class="list-unstyled">
                            <li class="mb-2"><i class="bx bx-check text-primary me-2"></i>
                                <strong>总参与人数：</strong>在选定时间范围内参与活动的去重用户数
                            </li>
                            <li class="mb-2"><i class="bx bx-check text-primary me-2"></i>
                                <strong>活动总数：</strong>在选定时间范围内有参与记录的活动数量
                            </li>
                            <li class="mb-2"><i class="bx bx-check text-primary me-2"></i>
                                <strong>平均参与率：</strong>总参与人数 / 系统中的活动总数 × 100%
                            </li>
                            <li class="mb-2"><i class="bx bx-check text-primary me-2"></i>
                                <strong>完成率：</strong>审核通过数 / (总参与数 - 未审核数 - 进行中数) × 100%
                            </li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h6 class="fw-bold">状态说明</h6>
                        <ul class="list-unstyled">
                            <li class="mb-2"><i class="bx bx-time text-warning me-2"></i>
                                <strong>未审核：</strong>用户已提交但管理员未审核的记录
                            </li>
                            <li class="mb-2"><i class="bx bx-play-circle text-info me-2"></i>
                                <strong>进行中：</strong>用户正在参与但未提交的活动
                            </li>
                            <li class="mb-2"><i class="bx bx-check-circle text-success me-2"></i>
                                <strong>已通过：</strong>管理员审核通过的记录
                            </li>
                            <li class="mb-2"><i class="bx bx-x-circle text-danger me-2"></i>
                                <strong>未通过：</strong>管理员审核不通过的记录
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="mt-3">
                    <h6 class="fw-bold">图表说明</h6>
                    <ul class="list-unstyled">
                        <li class="mb-2"><i class="bx bx-line-chart text-primary me-2"></i>
                            <strong>活动参与趋势：</strong>展示每日新增参与记录的数量变化
                        </li>
                        <li class="mb-2"><i class="bx bx-bar-chart text-primary me-2"></i>
                            <strong>热门活动排行：</strong>按参与人数降序排列的前5个活动
                        </li>
                        <li class="mb-2"><i class="bx bx-pie-chart text-primary me-2"></i>
                            <strong>参与状态分布：</strong>各状态记录数量的占比分布
                        </li>
                        <li class="mb-2"><i class="bx bx-bar-chart-alt-2 text-primary me-2"></i>
                            <strong>时段分布：</strong>24小时内各时段的参与记录数量分布
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- 图表区域 -->
    <div class="row g-4">
        <!-- 活动参与趋势 -->
        <div class="col-12 col-lg-8">
            <div class="card chart-card">
                <div class="card-header">
                    <h5 class="card-title mb-0">活动参与趋势</h5>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="participationTrendChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 活动参与排行 -->
        <div class="col-12 col-lg-4">
            <div class="card chart-card">
                <div class="card-header">
                    <h5 class="card-title mb-0">热门活动排行</h5>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="topActivitiesChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 参与状态分布 -->
        <div class="col-12 col-md-6">
            <div class="card chart-card">
                <div class="card-header">
                    <h5 class="card-title mb-0">参与状态分布</h5>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="statusDistributionChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 每日参与时段分布 -->
        <div class="col-12 col-md-6">
            <div class="card chart-card">
                <div class="card-header">
                    <h5 class="card-title mb-0">参与时段分布</h5>
                </div>
                <div class="card-body">
                    <div class="chart-container">
                        <canvas id="hourlyDistributionChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let charts = {};

// 加载统计数据
async function loadStatistics() {
    try {
        const timeRange = document.getElementById('timeRange').value;
        const status = document.getElementById('activityStatus').value;
        
        const response = await fetch(`/api/participation/statistics/?days=${timeRange}&status=${status}`);
        const data = await response.json();
        
        if (data.code === 200) {
            updateDashboardStats(data.data);
            updateCharts(data.data);
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

// 更新仪表板统计数据
function updateDashboardStats(data) {
    document.getElementById('totalParticipants').textContent = data.total_participants || 0;
    document.getElementById('totalActivities').textContent = data.total_activities || 0;
    document.getElementById('avgParticipationRate').textContent = `${data.avg_participation_rate || 0}%`;
    document.getElementById('completionRate').textContent = `${data.completion_rate || 0}%`;
    
    // 更新状态统计
    document.getElementById('pendingCount').textContent = data.status_counts.pending || 0;
    document.getElementById('ongoingCount').textContent = data.status_counts.ongoing || 0;
}

// 更新所有图表
function updateCharts(data) {
    // 活动参与趋势图
    updateTrendChart(data.trend_data);
    // 热门活动排行图
    updateTopActivitiesChart(data.top_activities);
    // 状态分布图
    updateStatusDistributionChart(data.status_distribution);
    // 时段分布图
    updateHourlyDistributionChart(data.hourly_distribution);
}

// 更新趋势图表
function updateTrendChart(data) {
    const labels = data.map(item => item.date);
    const values = data.map(item => item.count);

    charts.trend.data = {
        labels: labels,
        datasets: [{
            label: '参与人数',
            data: values,
            borderColor: '#696cff',
            backgroundColor: 'rgba(105, 108, 255, 0.1)',
            borderWidth: 2,
            fill: true,
            tension: 0.4
        }]
    };
    
    charts.trend.options = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: {
                    borderDash: [2, 2]
                }
            },
            x: {
                grid: {
                    display: false
                }
            }
        }
    };

    charts.trend.update();
}

// 更新热门活动排行图表
function updateTopActivitiesChart(data) {
    const labels = data.map(item => item.title);
    const values = data.map(item => item.count);

    charts.topActivities.data = {
        labels: labels,
        datasets: [{
            label: '参与次数',
            data: values,
            backgroundColor: '#696cff',
            borderRadius: 4
        }]
    };

    charts.topActivities.options = {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        },
        scales: {
            x: {
                beginAtZero: true,
                grid: {
                    borderDash: [2, 2]
                }
            },
            y: {
                grid: {
                    display: false
                }
            }
        }
    };

    charts.topActivities.update();
}

// 更新状态分布图表
function updateStatusDistributionChart(data) {
    const labels = data.map(item => item.status);
    const values = data.map(item => item.count);

    charts.statusDistribution.data = {
        labels: labels,
        datasets: [{
            data: values,
            backgroundColor: [
                '#696cff',  // 主色
                '#03c3ec',  // 信息
                '#71dd37',  // 成功
                '#ff3e1d'   // 危险
            ],
            borderWidth: 0
        }]
    };

    charts.statusDistribution.options = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'bottom'
            }
        },
        cutout: '60%'
    };

    charts.statusDistribution.update();
}

// 更新时段分布图表
function updateHourlyDistributionChart(data) {
    const labels = data.map(item => `${item.hour}:00`);
    const values = data.map(item => item.count);

    charts.hourlyDistribution.data = {
        labels: labels,
        datasets: [{
            label: '参与次数',
            data: values,
            backgroundColor: '#696cff',
            borderRadius: 4
        }]
    };

    charts.hourlyDistribution.options = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: {
                    borderDash: [2, 2]
                }
            },
            x: {
                grid: {
                    display: false
                }
            }
        }
    };

    charts.hourlyDistribution.update();
}

// 初始化图表
function initializeCharts() {
    // 活动参与趋势图
    charts.trend = new Chart(document.getElementById('participationTrendChart'), {
        type: 'line',
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });

    // 热门活动排行图
    charts.topActivities = new Chart(document.getElementById('topActivitiesChart'), {
        type: 'bar',
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false
        }
    });

    // 状态分布图
    charts.statusDistribution = new Chart(document.getElementById('statusDistributionChart'), {
        type: 'doughnut',
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });

    // 时段分布图
    charts.hourlyDistribution = new Chart(document.getElementById('hourlyDistributionChart'), {
        type: 'bar',
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
}

// 刷新数据
function refreshData() {
    loadStatistics();
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    initializeCharts();
    loadStatistics();
});
</script>
{% endblock %}

{% block nav_left %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}

{% block NavBar %}{% endblock %}

{% block footer %}{% include '后台管理/components/Footer.html' %}{% endblock %}
